﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZX.Web.UI.Controls;
using ZX.EHR.ResumeParseLib;
using System.Configuration;
using DevExpress.Web.ASPxUploadControl;
using System.IO;
using DevExpress.Web.ASPxClasses.Internal;
using System.Web.Caching;
using ZX.EHR.Library;
using System.Data;
using ZX.DAL.DBExtend;

namespace ZX.EHR.Web
{
    public partial class hrImportProjectWorkResult : BasePage
    {
        static string resFileName = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                UploadControl.ShowProgressPanel = true;
            }
            string flag = this.GetStringFromQueryString("flag", "");
            if (flag.Trim() == "save")
            {
                this.SaveData();
            }
        }

        protected void UploadControl_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
        {
            try
            {
                e.CallbackData = SavePostedFiles(e.UploadedFile);
            }
            catch (Exception ex)
            {
                e.IsValid = false;
                e.ErrorText = ex.Message;
            }
        }

        string SavePostedFiles(UploadedFile uploadedFile)
        {
            if (!uploadedFile.IsValid)
                return string.Empty;

            FileInfo fileInfo = new FileInfo(uploadedFile.FileName);
            string path = Request.PhysicalApplicationPath + "upload/EHR/";
            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
            }
            resFileName = path + fileInfo.Name;
            uploadedFile.SaveAs(resFileName);

            RemoveFileWithDelay(uploadedFile.FileName, resFileName, 5);
            string fileLabel = fileInfo.Name;
            string fileLength = uploadedFile.ContentLength / 1024 + "K";
            return string.Format("{0} ({1})|{2}", fileLabel, fileLength, fileInfo.Name);
        }



        static void RemoveFileWithDelay(string key, string fullPath, int delay)
        {
            if (HttpUtils.GetCache()[key] == null)
            {
                DateTime absoluteExpiration = DateTime.Now.Add(new TimeSpan(0, delay, 0));
                HttpUtils.GetCache().Insert(key, fullPath, null, absoluteExpiration,
                    Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, new CacheItemRemovedCallback(RemovedCallback));
            }
        }
        static void RemovedCallback(string key, object value, CacheItemRemovedReason reason)
        {
            if (File.Exists(value.ToString()))
                File.Delete(value.ToString());
        }

        protected void SaveData()
        {
            IList<DataTable> lstImportData = null;
            try
            {
                //读取EXCEL
                //string resFileName = Request.PhysicalApplicationPath + "upload/EHR/" + fileName;
                string employeeID = "", employeeName = "", employeeCode = "",yearMonth="";
                string Dat1 = "", Dat2 = "", Dat3 = "", Dat4 = "", Dat5 = "", Dat6 = "", Dat7 = "", Dat8 = "", Dat9 = "", Dat10 = "";
                string Dat11 = "", Dat12 = "", Dat13 = "", Dat14 = "", Dat15 = "", Dat16 = "", Dat17 = "", Dat18 = "", Dat19 = "", Dat20 = "";
                string Dat21 = "", Dat22 = "", Dat23 = "", Dat24 = "", Dat25 = "", Dat26 = "", Dat27 = "", Dat28 = "", Dat29 = "", Dat30 = "", Dat31 = "";
                int i = 0;

                string insetsql = @"INSERT INTO wkProjectWorkResult
                       ([ID],[Dat1],[Dat2],[Dat3],[Dat4],[Dat5],[Dat6],[Dat7],[Dat8],[Dat9],[Dat10],
                       [Dat11],[Dat12],[Dat13],[Dat14],[Dat15],[Dat16],[Dat17],[Dat18],[Dat19],[Dat20],
                       [Dat21],[Dat22],[Dat23],[Dat24],[Dat25],[Dat26],[Dat27],[Dat28],[Dat29],[Dat30],[Dat31],[EmployeeID],[YearMonth]) 
                       VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}','{17}',
                       '{18}','{19}','{20}','{21}','{22}','{23}','{24}','{25}','{26}','{27}','{28}','{29}','{30}','{31}','{32}','{33}')";

                if (resFileName != "")
                {
                    lstImportData = new List<DataTable>();
                    DbSql dbsql = new DbSql();
                    DataTable dtExcel = DbSql.ReadEcxel(resFileName, 1);
                    if (dtExcel != null && dtExcel.Rows.Count > 0)
                    {
                        lstImportData.Add(dtExcel);
                    }
                    foreach (DataTable dt in lstImportData)
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            string empCode = dr["员工编号"].ToString().Trim();
                            //工号为空则不再导入后续行
                            if (empCode == "")
                            {
                                break;
                            }
                            Dictionary<string, string> dicEmpInfo = GetEmpInfos(empCode);
                            if (dicEmpInfo.Count > 0)
                            {
                                employeeID = dicEmpInfo["EmployeeID"];
                                employeeName = dicEmpInfo["EmployeeName"];
                                employeeCode = dicEmpInfo["EmployeeCode"];
                                yearMonth = dr["年月"].ToString();
                                Dat1 = dr["Dat1"].ToString();
                                Dat2 = dr["Dat2"].ToString();
                                Dat3 = dr["Dat3"].ToString();
                                Dat4 = dr["Dat4"].ToString();
                                Dat5 = dr["Dat5"].ToString();
                                Dat6 = dr["Dat6"].ToString();
                                Dat7 = dr["Dat7"].ToString();
                                Dat8 = dr["Dat8"].ToString();
                                Dat9 = dr["Dat9"].ToString();
                                Dat10 = dr["Dat10"].ToString();
                                Dat11 = dr["Dat11"].ToString();
                                Dat12 = dr["Dat12"].ToString();
                                Dat13 = dr["Dat13"].ToString();
                                Dat14 = dr["Dat14"].ToString();
                                Dat15 = dr["Dat15"].ToString();
                                Dat16 = dr["Dat16"].ToString();
                                Dat17 = dr["Dat17"].ToString();
                                Dat18 = dr["Dat18"].ToString();
                                Dat19 = dr["Dat19"].ToString();
                                Dat20 = dr["Dat20"].ToString();
                                Dat21 = dr["Dat21"].ToString();
                                Dat22 = dr["Dat22"].ToString();
                                Dat23 = dr["Dat23"].ToString();
                                Dat24 = dr["Dat24"].ToString();
                                Dat25 = dr["Dat25"].ToString();
                                Dat26 = dr["Dat26"].ToString();
                                Dat27 = dr["Dat27"].ToString();
                                Dat28 = dr["Dat28"].ToString();
                                Dat29 = dr["Dat29"].ToString();
                                Dat30 = dr["Dat30"].ToString();
                                Dat31 = dr["Dat31"].ToString();

                                //先删除
                                string delsql = "delete from wkProjectWorkResult where EmployeeID='{0}' and YearMonth='{1}' ";
                                dbsql.ExecuteScalar(string.Format(delsql, employeeID, yearMonth));
                                //后写入
                                dbsql.ExecuteScalar(string.Format(insetsql, Guid.NewGuid().ToString(),
                                Dat1, Dat2, Dat3, Dat4, Dat5, Dat6, Dat7, Dat8, Dat9, Dat10,
                                Dat11, Dat12, Dat13, Dat14, Dat15, Dat16, Dat17, Dat18, Dat19, Dat20,
                                Dat21, Dat22, Dat23, Dat24, Dat25, Dat26, Dat27, Dat28, Dat29, Dat30, Dat31,
                                employeeID, yearMonth));
                                i++;
                            }
                        }
                    }
                    HttpContext.Current.Response.Write("1|" + i.ToString() + "|OK");
                }
                else
                {
                    HttpContext.Current.Response.Write("2");//文件未上传
                }
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write("0");
                throw ex;
            }
            finally
            {
                if (lstImportData != null)
                {
                    lstImportData.Clear();
                }
                resFileName = "";
            }
        }

        /// <summary>
        /// 根据导入的工号，匹配员工信息
        /// </summary>
        /// <param name="importEmpCode"></param>
        /// <returns></returns>
        protected Dictionary<string, string> GetEmpInfos(string importEmpCode)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            hrEmployee instance = ZX.Common.Globals.getEntity("hrEmployee") as hrEmployee;
            ZX.BLL.Extend.BaseBussnies hrBll = new ZX.BLL.Extend.BaseBussnies(instance);
            string condition = string.Format("EmployeeCode='{0}'", importEmpCode);
            ZX.EHR.Library.hrEmployee hrEmployee = hrBll.GetEntityByCondition(condition) as ZX.EHR.Library.hrEmployee;
            if (hrEmployee != null)
            {
                dic.Add("EmployeeID", hrEmployee.ID.ToString());
                dic.Add("EmployeeCode", hrEmployee.EmployeeCode);
                dic.Add("EmployeeName", hrEmployee.CName);
            }
            return dic;
        }

    }
}